import json

def merge(id_and_clusters):
    the_id = id_and_clusters.split('_')[0]
    clusters = id_and_clusters.split('_')[1]
    jsonFileName = "sourcedata/" + the_id + "_raw.json"
    idFileName = "sourcedata/" + the_id + "_matrixID.json"
    clusterFileName = "sourcedata/" + the_id + "_" + clusters + ".txt"
    f = open(idFileName, 'r')
    text = f.read()
    nodeId_2_matrixId = json.loads(text)
    f.close()
    f = open(clusterFileName, 'r')
    matrixId_2_cluster = ['do_not_use_index_0']
    for line in f.readlines():
        line = line[:-1]
        if line == "":
            break
        matrixId_2_cluster.append(line)
    f.close()
    f = open(jsonFileName, 'r')
    txt = f.read()
    source_dict = json.loads(txt.decode("utf8", 'replace'))
    f.close()
    nodes = source_dict.get('node')
    for key in nodes:
        node = nodes[key]
        if node['id'] == the_id:
            node['cluster'] = '300'
            print("root node found ...")
        else:
            node['cluster'] = matrixId_2_cluster[ nodeId_2_matrixId[node['id']] ]
    outFile = open("data/" + id_and_clusters + ".json", 'w')
    str2write = json.dumps(source_dict, ensure_ascii = False)
    outFile.write(str2write)
    outFile.close()
